﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MedicalManagementSystem.Utils;

namespace MedicalManagementSystem.Models
{
    public partial class PatientChart : IValidatable
    {
        public static PatientChart GetByPK(int id)
        {
            return DbContext.Instance.PatientChart.Where(patientChart => patientChart.id == id).FirstOrDefault();
        }

        #region Loaders
        public void LoadDiseaseNotes()
        {
            if (EntityState != System.Data.EntityState.Added && EntityState != System.Data.EntityState.Detached)
            {
                if (!this.DiseaseNotes.IsLoaded)
                {
                    DiseaseNotes.Load();
                }
            }
        }

        public void LoadPatient()
        {
            if (EntityState != System.Data.EntityState.Added && EntityState != System.Data.EntityState.Detached)
            {
                if (!this.PatientReference.IsLoaded)
                {
                    PatientReference.Load();
                }
            }
        }

        public void LoadDoctor()
        {
            if (EntityState != System.Data.EntityState.Added && EntityState != System.Data.EntityState.Detached)
            {
                if (!this.DoctorReference.IsLoaded)
                {
                    DoctorReference.Load();
                }
            }
        }

        public void Load()
        {
            LoadPatient();
            LoadDiseaseNotes();
            LoadDoctor();
        }
        #endregion

        public bool IsOld()
        {
            return this.DateLeave.HasValue;
        }

        public bool CheckBeforeSave()
        {
            return GetRuleViolations().Count() == 0;
        }

        public IEnumerable<IRuleViolation> GetRuleViolations()
        {
            LoadPatient();
            if (Patient == null)
            {
                //PatientList id выпадающего списка.
                yield return new RuleViolation("Необходимо выбрать пациента из списка.", this, "patientId", Patient);
            }
            if (DateArrive == DateTime.MinValue)
            {
                yield return new RuleViolation("Неверный формат даты.", this, "DateArrive", DateArrive);
            }
            else
            {
                if (DateArrive > DateTime.Now)
                    yield return new RuleViolation("Дата поступления должна быть не превосходить текущую.",this,"DateArrive",DateArrive);
            }

            if (DateLeave == DateTime.MinValue)
            {
                yield return new RuleViolation("Неверный формат даты.", this, "DateLeave", DateLeave);
            }
        }
    }
}
